package com.woyao;

import android.app.Application;
import android.app.ProgressDialog;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;

import com.woyao.core.model.GetMyMemberResponse;
import com.woyao.core.model.MemberSummary;
import com.woyao.core.model.Tag;
import com.woyao.core.service.AccountService;
import com.woyao.core.util.ServiceFactory;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;

import static android.content.Context.MODE_PRIVATE;
import static com.woyao.WoyaoooApplication.userId;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link MemberFragment.OnMemberFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link MemberFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MemberFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public UserViewModel uvm;

    private MemberAdapter allAdapter;
    private RecyclerView alllist = null;
    LinearLayoutManager allLayoutManager = null;

    FrameLayout emptyArea;

    private TagAdapter tagAdapter;
    private RecyclerView tagList = null;
    LinearLayoutManager tagLayoutManager = null;
    private String type ="";

    List<MemberSummary> myMembers = new ArrayList<MemberSummary>();

    Button addOrg;
    
    FrameLayout theview;
    Toolbar toolbar;

    private Integer ADD_MEMBER_CODE = 2000;
    private Integer ADD_DEMAND_CODE = 2000;
    private Integer GET_CODE = 300;
    private Integer MYREGISTER_CODE = 600;

    ProgressDialog progressDialog;
    private boolean changed = false;


    private OnMemberFragmentInteractionListener mListener;


    public MemberFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment MessageFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static MemberFragment newInstance(String param1, String param2) {
        MemberFragment fragment = new MemberFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }



    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        theview = (FrameLayout) inflater.inflate(R.layout.fragment_member, container, false);

        toolbar = (Toolbar) theview.findViewById(R.id.toolBar);
////        toolbar.setLogo(R.drawable.ic_launcher);
        toolbar.setTitle("组织");
        toolbar.inflateMenu(R.menu.chance);

        Menu menu = toolbar.getMenu();
        if (menu != null) {
            try {
                //如果不为空,就反射拿到menu的setOptionalIconsVisible方法
                Method method = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
                //暴力访问该方法
                method.setAccessible(true);
                //调用该方法显示icon
                method.invoke(menu, true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                if (item.getItemId() == R.id.nav_search) {
                    Intent intent = new Intent();
                    intent.setClass(getContext(), SearchActivity.class);
                    startActivity(intent);
                }


                if (item.getItemId() == R.id.nav_publish_demand) {
                    if (!WoyaoooApplication.hasLogin){
                        Intent intent = new Intent();
                        intent.setClass(getContext(), RegisterActivity.class);
                        startActivityForResult(intent,MYREGISTER_CODE);
                        return false;
                    }
                    Intent intent = new Intent();
                    intent.putExtra("from", "chance"  );
                    intent.putExtra("is_new", true);
                    intent.setClass(getContext(), DemandNewActivity.class);
                    startActivityForResult(intent, ADD_DEMAND_CODE);
                }
                if (item.getItemId() == R.id.nav_add_member) {
                    if (!WoyaoooApplication.hasLogin){
                        Intent intent = new Intent();
                        intent.setClass(getContext(), RegisterActivity.class);
                        startActivityForResult(intent,MYREGISTER_CODE);
                        return false;
                    }
                    Intent intent = new Intent();
                    intent.setClass(getContext(), ConfirmOrgActivity.class);
                    startActivityForResult(intent,ADD_MEMBER_CODE);
                }

//                if (item.getItemId() == R.id.nav_add_user) {
//                    Intent intent = new Intent();
//                    intent.setClass(getContext(), InviteActivity.class);
//                    startActivity(intent);
//                }

                if (item.getItemId() == R.id.nav_add_partner) {
                  if (!WoyaoooApplication.hasLogin){
                        Intent intent = new Intent();
                        intent.setClass(getContext(), RegisterActivity.class);
                        startActivityForResult(intent,MYREGISTER_CODE);
                        return false;
                    }
//                    mListener.onTabChance(R.id.cooperate);
                    Intent intent = new Intent();
                    intent.setClass(getContext(), RelationActivity.class);
                    intent.putExtra("is_new",true);
                    startActivity(intent);
                }
                return false;
            }
        });
        emptyArea = (FrameLayout) theview.findViewById(R.id.empty_area);

        alllist = (RecyclerView)theview.findViewById(R.id.member_items);
        allLayoutManager = new LinearLayoutManager(getContext());
        allLayoutManager.setOrientation(OrientationHelper.VERTICAL);
        alllist.setLayoutManager(allLayoutManager);
        alllist.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL_LIST));



        addOrg = (Button) theview.findViewById(R.id.member_add);
        addOrg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!WoyaoooApplication.hasLogin){
                    Intent intent = new Intent();
                    intent.setClass(getContext(), RegisterActivity.class);
                    startActivityForResult(intent,MYREGISTER_CODE);
                    return ;
                }
                Intent intent = new Intent();
                intent.putExtra("from","mymember");
                intent.putExtra("id",0);
                intent.setClass(getContext(), ConfirmOrgActivity.class);

                startActivityForResult(intent, ADD_MEMBER_CODE);
            }
        });

        tagList = (RecyclerView)theview.findViewById(R.id.id_mytags);
        tagLayoutManager = new LinearLayoutManager(getContext());
        tagLayoutManager.setOrientation(OrientationHelper.HORIZONTAL);
        tagList.setLayoutManager(tagLayoutManager);
        tagList.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.HORIZONTAL_LIST));


        loadData("");


        return theview;
    }



    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        uvm = ViewModelProviders.of(getActivity()).get(UserViewModel.class);
    }


    private void getIt( final Integer curid ){
        Intent intent = new Intent();
        intent.setClass(getContext(), MemberActivity.class);
        intent.putExtra("id", curid  );
        startActivityForResult(intent,GET_CODE);

    }
    private AsyncTask<Void,Void, GetMyMemberResponse> task = null;
    public void loadData( final String status){
        if(task != null)return;

        progressDialog = new ProgressDialog(getContext());
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("正在获取数据······");
        progressDialog.show();

        task =new AsyncTask<Void, Void, GetMyMemberResponse>() {
            @Override
            protected GetMyMemberResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<GetMyMemberResponse> responseCall = svc.getMyMember(userId,status,"mgmt");
                try {
                    GetMyMemberResponse response = responseCall.execute().body();
                    return response;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onPostExecute(final GetMyMemberResponse response) {
                progressDialog.dismiss();
                renderMember(response);
                task = null;
            }
            @Override
            protected void onCancelled() {
                progressDialog.dismiss();
            }
        };
        task.execute((Void)null);
    }
    private void renderMember(GetMyMemberResponse response){
        myMembers = response.getContent();
        toolbar.setTitle( response.getMessage() );

        Integer position = 0 ;
        for (Tag tg : response.getStatis() ){

            if (tg.getSelected()){
                break;
            }
            position += 1;
        }
        tagAdapter = new TagAdapter(getContext(),getResources(), response.getStatis());
        tagAdapter.setChangedHandler(new TagAdapter.Changed() {
            @Override
            public void itemSelected(Tag one) {
                type = one.getId();
                loadData(one.getId());
            }
        });

        tagList.scrollToPosition( position );

        tagList.setAdapter(tagAdapter);

        if (response.getContent().size() == 0 ){
            emptyArea.setVisibility(View.VISIBLE);
            alllist.setVisibility(View.GONE);
        }else {
            emptyArea.setVisibility(View.GONE);
            alllist.setVisibility(View.VISIBLE);
            allAdapter = new MemberAdapter(getContext(), response.getContent());

            allAdapter.setChangedHandler(new MemberAdapter.Changed() {
                @Override
                public void view(MemberSummary ms) {

                    getIt(ms.getId());

                }


            });

            alllist.setAdapter(allAdapter);
        }


    }
    

    @Override
    public void onResume() {
        loadUserBasic();
        super.onResume();

    }

    private void loadUserBasic(){
        Application application = getActivity().getApplication();
        SharedPreferences shared = application.getSharedPreferences("login", MODE_PRIVATE);

            try {
                WoyaoooApplication.hasLogin = shared.getBoolean("logged", false);
                WoyaoooApplication.userId = shared.getInt("userId", 0);
                WoyaoooApplication.displayname = shared.getString("displayname", "");;
                WoyaoooApplication.location = shared.getString("location", "");
                WoyaoooApplication.title = shared.getString("title", "");
                WoyaoooApplication.snailview = shared.getString("snailview", "");
                WoyaoooApplication.demand_id = shared.getInt("demand_id", 0);
                WoyaoooApplication.member_id = shared.getInt("member_id", 0);
                WoyaoooApplication.message_num = shared.getInt("message_num", 0);

            }catch (Exception e){

            }

    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onMemberFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnMemberFragmentInteractionListener) {
            mListener = (OnMemberFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnMemberFragmentInteractionListener {
        // TODO: Update argument type and name
        void onMemberFragmentInteraction(Uri uri);
        void onMessage( Integer messageNum, String info);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == GET_CODE  || requestCode == ADD_MEMBER_CODE ) {

            Boolean ischanged = data.getBooleanExtra("changed", true);
            if (ischanged) {
                loadData("");
                changed = true;
            }
        }
    }
}
